import { useCurrentEditor } from "@tiptap/react"
import { Tooltip, Button, Typography } from "antd"
import { CSSProperties, ReactElement, useEffect, useState } from "react"
import CustomIcon from "../../CustomIcon"
import LinkModal from "../LinkModal"
import {ToC} from "../../ToC"
import React from "react"
// import { ReactComponent as FontColorSvg } from '../../assets/fontColor.svg'
type SELECT_OPTIONS = {
    label: string,
    value: 1 | 2 | 3 | 4 | 5 | any,
    command: () => void,
    isActive?: string,
    disabled?: any,
    icon?: string,
}
type BTNS = {
    name: string,
    icon: string | ReactElement,
    command: () => void,
    isActive: string,
    disabled: any,
    style?: CSSProperties,
    type?: string
    options?: SELECT_OPTIONS[]
}
const MemorizedToC = React.memo(ToC)

const EditBtns = ({getEditHTML,items,isToC}:{getEditHTML:(str: string) => void;items?:any;isToC:boolean}) => {
    const { Title } = Typography
    const { editor }: any = useCurrentEditor()
    const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
    const [btnValue, setBtnValue] = useState('正文')
    const [alignmentIcon, setAlignmentIcon] = useState({ icon: 'align-left', label: '左对齐' })
    const [isOpen, setIsOpen] = useState(false)
    useEffect(() => {
        const updata = () => {
            getEditHTML&&getEditHTML(editor.getHTML())
        }
        editor.on('update', updata)
        return () => {
            editor.off('update', updata);
        };
    }, [editor])
    useEffect(() => {
        // 监听标题变化的函数
        const selectionUpdate = () => {
            const currentEditType = editor.state.selection.$head.parent.type.name;
            const currentTextAlign = editor.state.selection.$head.parent.attrs.textAlign;
            switch (currentEditType) {
                case 'paragraph':
                    setBtnValue('正文')
                    break;
                case 'heading':
                    setBtnValue(`标题${editor.state.selection.$head.parent.attrs.level}`)
                    break;
            }
            switch (currentTextAlign) {
                case 'left':
                    setAlignmentIcon({ icon: 'align-left', label: '左对齐' })
                    break;
                case 'center':
                    setAlignmentIcon({ icon: 'align-center', label: '居中对齐' })
                    break;
                case 'right':
                    setAlignmentIcon({ icon: 'align-right', label: '右对齐' })
                    break;
                case 'justify':
                    setAlignmentIcon({ icon: 'align-justify', label: '两端对齐' })
                    break;
            }
        }
        editor.on('selectionUpdate', selectionUpdate)
        return () => {
            editor.off('selectionChange', selectionUpdate);
        };
    }, [editor]);
    if (!editor) {
        return null
    }
    const getLinkValues = ({ text, url }: { text: string, url: string }) => {
        editor.commands.insertContent(`<a href="${url}">${text}</a>`,
            {
                parseOptions: {
                    preserveWhitespace: false,
                }
            })
    }
    const CreateBtns = () => {
        const btns: BTNS[] = [
            {
                name: '加粗',
                icon: 'bold',
                command: () => editor.chain().focus().toggleBold().run(),
                isActive: 'bold',
                disabled: !editor.can().chain().focus().toggleBold().run()

            },
            {
                name: '斜体',
                icon: 'italic',
                command: () => editor.chain().focus().toggleItalic().run(),
                isActive: 'italic',
                disabled: !editor.can()
                    .chain()
                    .focus()
                    .toggleItalic()
                    .run()

            },
            {
                name: '下划线',
                icon: 'underline',
                command: () => editor.chain().focus().toggleUnderline().run(),
                isActive: 'underline',
                disabled: null
            },
            {
                name: '链接',
                icon: 'link',
                command: () => setIsModalOpen(true),
                isActive: 'link',
                disabled: null
            },
            {
                name: '删除线',
                icon: 'strikethrough',
                command: () => editor.chain().focus().toggleStrike().run(),
                isActive: 'strike',
                disabled: !editor.can()
                    .chain()
                    .focus()
                    .toggleStrike()
                    .run()
            },
            {
                name: '代码',
                icon: 'code-view',
                command: () => editor.chain().focus().toggleCode().run(),
                isActive: 'code',
                disabled: !editor.can()
                    .chain()
                    .focus()
                    .toggleCode()
                    .run()
            },
            {
                name: '代码块',
                icon: 'terminal-box-line',
                command: () => {
                    editor.chain().focus().toggleCodeBlock().run();
                    // editor.chain().focus().setHardBreak().run();
                },
                isActive: 'codeBlock',
                disabled: null
            },
            {
                name: '表格',
                icon: 'table-line',
                command: ()=>{},
                isActive: 'table',
                disabled: null
            },
            {
                type: 'select',
                name: '正文',
                icon: '',
                command: () => { },
                isActive: '',
                disabled: null,
                options: [
                    {
                        label: '正文',
                        value: 'paragraph',
                        command: () => editor.chain().focus().setParagraph().run(),
                        isActive: 'paragraph',
                    },
                    {
                        label: '标题1',
                        value: 1,
                        command: () => editor.chain().focus().toggleHeading({ level: 1 }).run(),
                        isActive: 'heading',
                    },
                    {
                        label: '标题2',
                        value: 2,
                        command: () => editor.chain().focus().toggleHeading({ level: 2 }).run(),
                        isActive: 'heading',
                    },
                    {
                        label: '标题3',
                        value: 3,
                        command: () => editor.chain().focus().toggleHeading({ level: 3 }).run(),
                        isActive: 'heading',
                    },
                    {
                        label: '标题4',
                        value: 4,
                        command: () => editor.chain().focus().toggleHeading({ level: 4 }).run(),
                        isActive: 'heading',
                    },
                    {
                        label: '标题5',
                        value: 5,
                        command: () => editor.chain().focus().toggleHeading({ level: 5 }).run(),
                        isActive: 'heading',
                    },
                ]
            },
            {
                name: '无序列表',
                icon: 'list-unordered',
                command: () => editor.chain().focus().toggleBulletList().run(),
                isActive: 'bulletList',
                disabled: null
            },
            {
                name: '有序列表',
                icon: 'list-ordered-2',
                command: () => editor.chain().focus().toggleOrderedList().run(),
                isActive: 'orderedList',
                disabled: null
            },
            {
                name: '块引用',
                icon: 'double-quotes-l',
                command: () => editor.chain().focus().toggleBlockquote().run(),
                isActive: 'blockquote',
                disabled: null
            },
            {
                name: '分割线',
                icon: 'subtract-line',
                command: () => editor.chain().focus().setHorizontalRule().run(),
                isActive: '',
                disabled: null
            },

            // {
            //     name: '字体颜色',
            //     icon: <FontColorSvg/>,
            //     command: () => editor.chain().focus().setColor('#958DF1').run(),
            //     isActive: '',
            //     disabled: null
            // },
            {
                name: '任务列表',
                icon: 'task-line',
                command: () => editor.chain().focus().toggleTaskList().run(),
                isActive: 'taskList',
                disabled: null
            },
            {
                type: 'alignment',
                name: '',
                icon: '',
                command: () => { },
                isActive: '',
                disabled: null,
                options: [
                    {
                        label: '左对齐',
                        value: 'left',
                        command: () => editor.chain().focus().setParagraph().run(),
                        icon: 'align-left'
                    },
                    {
                        label: '居中',
                        value: 'center',
                        command: () => editor.chain().focus().toggleHeading({ level: 1 }).run(),
                        icon: 'align-center'
                    },
                    {
                        label: '右对齐',
                        value: 'right',
                        command: () => editor.chain().focus().toggleHeading({ level: 2 }).run(),
                        icon: 'align-right'
                    },
                    {
                        label: '两端对齐',
                        value: 'justify',
                        command: () => editor.chain().focus().toggleHeading({ level: 2 }).run(),
                        icon: 'align-justify'
                    },
                ]
            },
        ]
        const btnClick = (fn: () => void, valule: string) => {
            fn();
            setBtnValue(pre => (pre === valule ? '正文' : valule));
        }
        return <>
            {btns.map((item: BTNS) => {
                switch (item.type) {
                    case 'select':
                        return <span key={item.name} className='btnsBox'>
                            <Button className="btns" >
                                {btnValue} <CustomIcon str={"arrow-down-s-line"} />
                            </Button>
                            <div className="btnsList">
                                {item.options?.map((item) => {
                                    return <Title
                                        key={item.label}
                                        onClick={() => btnClick(item.command, item.label)}
                                        className={
                                            (typeof item.value === 'string' ? editor.isActive(item.isActive)
                                                : editor.isActive('heading', { level: item.value }))
                                                ? 'is-btn-active' : ''}
                                        level={typeof item.value === 'string' ? 4 : item.value}
                                    >{item.label}</Title>
                                })}
                            </div>
                        </span>
                    case 'alignment':
                        return <span key={item.name} className='alignmentBox'>
                            <Button onClick={() => { setIsOpen(pre => !pre) }} >
                                <CustomIcon str={alignmentIcon.icon} /><span style={{ fontSize: 14, padding: 5 }}>{alignmentIcon.label}</span>
                                <CustomIcon str={"arrow-down-s-line"} />
                            </Button>
                            {isOpen && <div className="btnsList">
                                {item.options?.map((item) => {
                                    return <Tooltip key={item.label} placement="bottom" arrow={false} title={<span className="tooltip">{item.label}</span>}>
                                        <Button onClick={() => {
                                            editor.chain().focus().setTextAlign(item.value).run();
                                            item.icon && setAlignmentIcon({ icon: item.icon, label: item.label });
                                        }}
                                            className={editor.isActive({ textAlign: item.value }) ? 'is-active' : ''}>
                                            <CustomIcon str={item.icon} /><span style={{ fontSize: 14, padding: 5 }}>{item.label}</span>
                                        </Button>
                                    </Tooltip>
                                })}
                            </div>}
                        </span>
                    default:
                        return <Tooltip key={item.name} placement="bottom" arrow={false} title={<span className="tooltip">{item.name}</span>}>
                            <Button
                                style={{ marginBottom: 5 }}
                                onClick={item.command}
                                disabled={item.disabled}
                                className={editor.isActive(item.isActive) ? 'is-active' : ''}
                            >
                                <CustomIcon str={item.icon} />
                            </Button>
                        </Tooltip>
                }

            })}
        </>
    }
    return <div className="menuList">
        {isToC&&<div className="table-of-content">
        <MemorizedToC editor={editor} items={items} />
      </div>}
        {CreateBtns()}
        {/* <MyEditorWithTOC/> */}
        <LinkModal getLinkValues={getLinkValues} isModalOpen={isModalOpen} setIsModalOpen={setIsModalOpen} />
    </div>

    // <>
    //     {}

    //     {/* <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" stroke='red' strokeWidth="1" ><path d="M15.2459 14H8.75407L7.15407 18H5L11 3H13L19 18H16.8459L15.2459 14ZM14.4459 12L12 5.88516L9.55407 12H14.4459ZM3 20H21V22H3V20Z"></path></svg> */}
    //     {/* <button onClick={() => editor.chain().focus().unsetAllMarks().run()}>
    //         清楚字体效果
    //     </button>
    //     <button onClick={() => editor.chain().focus().clearNodes().run()}>
    //         清空格式
    //     </button> */}
    //     {/* <button
    //         onClick={() => editor.chain().focus().setParagraph().run()}
    //         className={editor.isActive('paragraph') ? 'is-active' : ''}
    //     >
    //         段落 正文
    //     </button> */}
    //     {/* <button onClick={() => editor.chain().focus().setHardBreak().run()}>
    //         换行
    //     </button> */}
    //     {/* <button
    //         onClick={() => editor.chain().focus().undo().run()}
    //         disabled={
    //             !editor.can()
    //                 .chain()
    //                 .focus()
    //                 .undo()
    //                 .run()
    //         }
    //     >
    //         undo 撤回
    //     </button>
    //     <button
    //         onClick={() => editor.chain().focus().redo().run()}
    //         disabled={
    //             !editor.can()
    //                 .chain()
    //                 .focus()
    //                 .redo()
    //                 .run()
    //         }
    //     >
    //         redo 撤销撤回
    //     </button> */}
    //     {/* <button
    //         onClick={}
    //         className={editor.isActive('textStyle', { color: '#958DF1' }) ? 'is-active' : ''}
    //     >
    //         purple 配置选中文字颜色
    //     </button> */}
    // </>
}

export default EditBtns